<?php
/**
 * Created by PhpStorm.
 * User: nathan
 * Date: 2019/2/13
 * Time: 11:43
 */

namespace Refine\Service;

use Refine\Iplookup\IplookupInterface;
use Psr\Log\LoggerInterface;
use Psr\SimpleCache\CacheInterface;

/**
 * Class IplookupService
 * @package Refine\Service
 */
class IplookupService implements IplookupInterface
{
    /**
     * @var CacheInterface
     */
    protected $cache;
    /**
     * @var IplookupInterface
     */
    protected $iplookup;
    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * IplookupService constructor.
     * @param array $options
     */
    public function __construct($options)
    {
        $this->iplookup = $options['iplookup'];
        $this->cache = $options['cache'];
        $this->logger = $options['logger'];
    }

    /**
     * @param string $ip
     * @return string
     */
    public function lookup($ip)
    {
        $this->logger->info(sprintf('query %s', $ip));
        $key = md5($ip);
        if ($this->cache->has($key)) {
            $result = $this->cache->get($key);
        } else {
            $result = $this->iplookup->lookup($ip);
            $this->cache->set($key, $result);
        }
        $this->logger->info(sprintf('%s is %s', $ip, $result));
        return $result;
    }

}